package net.meblabs.bookapp.data.dao;

import java.util.List;

import javax.sql.DataSource;

import net.meblabs.bookapp.data.Hint;
import net.meblabs.bookapp.data.HintRowMapper;
import net.meblabs.bookapp.data.model.Book;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
@SuppressWarnings("unchecked")
public class BookDaoImpl extends HibernateDaoSupport implements BookDao {

	private JdbcTemplate jdbcTemplate;

	@Autowired
	public BookDaoImpl(SessionFactory sessionFactory) {
		setSessionFactory(sessionFactory);
	}

	@Autowired
	public void setDataSource(DataSource dataSource) {
		jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	public List<Book> find() {
		Session session = SessionFactoryUtils.getSession(getSessionFactory(), false);
		return session.createQuery("from Book").list();
	}

	@Override
	public Book findById(Long id) {
		Session session = SessionFactoryUtils.getSession(getSessionFactory(), false);
		return (Book) session.load(Book.class, id);
	}

	@Override
	public void save(Book book) {
		getHibernateTemplate().saveOrUpdate(book);
	}

	@Override
	public List<Hint> findAuthorsAutocomplete(String term) {
		return jdbcTemplate.query(
				"select id value, concat(concat(lname, ','), fname) label from bt_author"
						+ " where lower(concat(concat(lname, ','), fname)) like ?",
				new Object[] { term + "%" }, new HintRowMapper());
	}
}
